package org.xiaom.butler.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * HttpServletRequest帮助类
 * 
 * @author XM
 * 
 */
public abstract class Util {
	 

	/**
	 * @param request
	 * @param name
	 * @param defaultValue
	 *            如果没有此参数，需要返回的默认值
	 * @return
	 */
	public static String getQueryParam(HttpServletRequest request, String name,
			String defaultValue) {
		String rs = request.getParameter(name);
		rs=rs==null?"":rs;
		try {
			new String(rs.getBytes("iso-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return isBlank(rs) ? defaultValue : rs;
	}

	/**
	 * 7 string==null || "".equals(string)
	 */
	public static boolean isBlank(String str) {
		return str == null || "".equals(str);
	}

	/**
	 * 转向提示网页
	 */
	public static void redirectToErrorPage(HttpServletRequest request,
			HttpServletResponse response, String msg) {
		try {
			request.getSession().setAttribute("error_message", msg);
			response.sendRedirect(request.getContextPath()+"/error.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * forward
	 */
	public static void forward(ServletContext context,
			HttpServletRequest request, HttpServletResponse response,
			String path, boolean full) {

		try {
			if (full) {
				context.getRequestDispatcher(path).forward(request, response);
			} else {
				context.getRequestDispatcher(Standard.JSP_PATH_PREFIX + path)
						.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectToErrorPage(request, response, "错误的请求");
		}
	}

	/**
	 * forward
	 */
	public static void redirect(HttpServletRequest request,
			HttpServletResponse response, String path, boolean full) {
		try {
			if (full) {
				response.sendRedirect(Standard.JSP_PATH_PREFIX + path);
			} else {
				response.sendRedirect(path);
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectToErrorPage(request, response, "错误的请求");
		}
	}
}
